package com.jiangnan.warehouse_management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangnan.warehouse_management.common.exception.BusinessException;
import com.jiangnan.warehouse_management.dto.request.RegisterRequest;
import com.jiangnan.warehouse_management.dto.request.UpdatePasswordRequest;
import com.jiangnan.warehouse_management.dto.request.UpdateUserRequest;
import com.jiangnan.warehouse_management.dto.request.UserQueryRequest;
import com.jiangnan.warehouse_management.dto.response.LoginResponse.UserDTO;
import com.jiangnan.warehouse_management.dto.response.RegisterResponse;
import com.jiangnan.warehouse_management.dto.response.UserQueryResponse;
import com.jiangnan.warehouse_management.mapper.UserMapper;
import com.jiangnan.warehouse_management.pojo.User;
import com.jiangnan.warehouse_management.service.UserService;
import com.jiangnan.warehouse_management.utils.MD5Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final MD5Utils md5Utils;

    @Override
    public UserDTO findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) return null;
        
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(user, dto);
        return dto;
    }

    @Override
    @Transactional
    public RegisterResponse register(RegisterRequest request) {
        // 加密密码
        String encryptedPassword = md5Utils.encrypt(request.getPassword());
        request.setPassword(encryptedPassword);

        // 执行注册
        userMapper.register(request);

        // 查询注册后的用户信息
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new BusinessException(400, "注册失败");
        }

        // 构建响应
        RegisterResponse response = new RegisterResponse();
        BeanUtils.copyProperties(user, response);
        return response;
    }

    @Override
    public UserQueryResponse listUsers(UserQueryRequest request) {
        // 参数校验和默认值设置
        Integer page = request.getPage();
        Integer pageSize = request.getPageSize();
        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 构建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(request.getUsername())) {
            wrapper.like(User::getUsername, request.getUsername());
        }
        if (StringUtils.hasText(request.getRole())) {
            wrapper.eq(User::getRole, request.getRole());
        }

        // 开启分页（使用PageHelper）
        PageHelper.startPage(page, pageSize, true);

        // 执行查询
        List<User> users = userMapper.selectList(wrapper);

        // 获取分页信息
        PageInfo<User> pageInfo = new PageInfo<>(users);

        // 构建响应
        UserQueryResponse response = new UserQueryResponse();
        response.setTotal(pageInfo.getTotal());
        response.setPage(page);
        response.setPageSize(pageSize);

        List<UserQueryResponse.QueryUserDTO> userList = users.stream()
                .map(user -> {
                    UserQueryResponse.QueryUserDTO dto = new UserQueryResponse.QueryUserDTO();
                    BeanUtils.copyProperties(user, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        response.setList(userList);

        return response;
    }

    @Override
    public UserQueryResponse.QueryUserDTO findById(int id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }

        UserQueryResponse.QueryUserDTO dto = new UserQueryResponse.QueryUserDTO();
        BeanUtils.copyProperties(user, dto);
        return dto;
    }

    @Override
    @Transactional
    public void updateUserPwd(int userId, UpdatePasswordRequest request) {
        // 查询用户
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }

        // 验证原密码
        if (!md5Utils.verify(request.getOldPassword(), user.getPassword())) {
            throw new BusinessException(400, "原密码错误");
        }

        // 验证新密码强度
        if (request.getNewPassword() == null || request.getNewPassword().length() < 6) {
            throw new BusinessException(400, "新密码长度不能少于6位");
        }

        // 加密新密码并更新
        String encryptedNewPwd = md5Utils.encrypt(request.getNewPassword());
        userMapper.updatePwd(userId, encryptedNewPwd);
    }

    @Override
    @Transactional
    public UserQueryResponse.QueryUserDTO updateUserInfo(UpdateUserRequest request) {
        // 查询用户
        User user = userMapper.selectById(request.getUserId());
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }

        // 更新用户信息
        if (StringUtils.hasText(request.getRealName())) {
            user.setRealName(request.getRealName());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }

        // 保存更新
        userMapper.updateById(user);

        // 构建响应
        UserQueryResponse.QueryUserDTO dto = new UserQueryResponse.QueryUserDTO();
        BeanUtils.copyProperties(user, dto);
        return dto;
    }

    @Override
    @Transactional
    public void deleteUser(int id) {
        // 查询用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }

        // 执行删除
        userMapper.deleteById(id);
    }
}